#include "lyric.h"
#include "base64.h"
#include "curlrequest.h"
#include <fcntl.h>
#include <jansson.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define URL_LYRIC "https://u.y.qq.com/cgi-bin/musicu.fcg"

char* get_song_mid(char* key, int p_try_time_index) /* 获取歌词 */
{
    char* data = "{\"req_1\": {\"method\": \"DoSearchForQQMusicDesktop\",\"module\": \"music.search.SearchCgiService\",\"param\": {\"num_per_page\": \"2\",\"page_num\": \"1\",\"query\": \"%s\",\"search_type\": 0}}}";
    char buf[1208] = { 0 };
    char* mid = malloc(sizeof(char) * 1280);
    memset(mid, 0, 1280);
    sprintf(buf, data, key);
    /* printf("buf:%s\n", buf); */
    char* resp = Request(POST, URL_LYRIC, buf, NULL, 0);
    /* printf(resp); */
    /* FILE* fp = fopen("resp.json", "wb"); */
    /* if (fp == NULL) { */
    /*     printf("can't open failed!!"); */
    /*     return NULL; */
    /* } */
    /*  */
    /* fwrite(resp, 1, strlen(resp) + 1, fp); */
    /* fclose(fp); */
    json_error_t error;
    json_t* root = json_loads(resp, 0, &error);
    if (root) {
        json_t* value = json_object_get(root, "req_1");
        value = json_object_get(value, "data");
        value = json_object_get(value, "body");
        value = json_object_get(value, "song");
        value = json_object_get(value, "list");
        if (json_is_array(value)) {
            /* printf("size is %d\n", json_array_size(value)); */
            if (p_try_time_index > json_array_size(value) - 1)
            {
                return NULL;
            }
            value = json_array_get(value, p_try_time_index);
            value = json_object_get(value, "mid");
            if (json_is_string(value)) {
                strcpy(mid, json_string_value(value));
                /* printf("mid:%s\n", mid); */
                json_decref(root);
                return mid;
            }
        }
    }
    /* json_decref(root); */
    return NULL;
}

static char* guolv(char* buf)
{
    char* p = strstr(buf, "[offset:0]");
    if (index >= 0) {
        return p + strlen("[offset:0]") + 1;
    }
    return NULL;
}

char* get_lyric(char* songmid)
{
    // ?callback=MusicJsonCallback&g_tk=5381&songmid=001nUzRq0GgCVb&json=1&utf8=1
    char tmp[1280] = { 0 };
    const char* url = "https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg";
    char* param = "%s?callback=MusicJsonCallback&g_tk=5381&songmid=%s&json=1&utf8=1";
    sprintf(tmp, param, url, songmid);
    /* printf("tmp: %s", tmp); */
    char* headers[2] = { "Referer: https://y.qq.com/portal/player.html" };
    char* resp = Request(GET, tmp, NULL, headers, 1);
    char buf[7240] = { 0 };
    /* printf(resp); */
    char* p = strstr(resp, "\"lyric\":\"");
    if (p == NULL) {
        /* 找不到lyric这个关键字的话，则为报错 */
        return NULL;
    }
    sscanf(p + 9, "%[^\"]", buf);
    /* json_error_t error; */
    /* json_t *root = json_loads(ptr, 0, &error); */
    /* if (root) { */
    /*     json_t *value = json_object_get(root, "key"); */
    /*     if (json_is_string(value)) { */
    /*         const char *str_value = json_string_value(value); */
    /*         printf("Value: %s\n", str_value); */
    /*     } */
    /* } */
    char outdata[19000] = { 0 };
    int n;
    base64_decode(buf, strlen(buf), outdata, &n);

    /* printf("buf:%s\n", buf); */
    char* output_p = guolv(outdata);
    /* printf("%s\n", guolv(outdata)); */
    return output_p;
    /* return resp; */
}

enum ERROR_DOWNLOAD_LRC {
    ERROR_CODE_LYRIC_MID = 1,
    ERROR_CODE_LYRIC_OPENFILE,
    ERROR_CODE_LYRIC_OUTPUT
};

/*
 * download_lrc 用于下载歌词
 *
 * key：要搜索的关键字
 */
int download_lrc(char* key, const char* target_file)
{
    /* printf("%s\n", t); */
    /* printf("sss\n"); */
    /* printf("%s\n", t); */
    /* printf("target_file: %s", target_file); */
    /* printf("key: %s\n", key); */
    char* t = (char*)malloc(sizeof(char) * strlen(target_file) + 1);
    strcpy(t, target_file);
    /* printf("t: %s\n", t); */
    int try_time_index = 0;
    int cout = 0;
    char* output_p = NULL;
    while (1) {
        /* printf("try the %d time",  try_time_index); */
        char* song_mid = get_song_mid(key, try_time_index);
        try_time_index++;
        /* printf("song_mid: %s", song_mid); */
        /* char * song_mid = "xxx"; */
        /* printf("t: %s\n", t); */
        if (song_mid == NULL) {
            printf("can't get song mid!!\n");
            return ERROR_CODE_LYRIC_MID;
        }
        output_p = get_lyric(song_mid);
        if (output_p == NULL && cout++ > 2) {
            printf("\033[41m找不到, 次数已经超过!!\033[0m\n");
            return ERROR_CODE_LYRIC_OUTPUT;
        }
        if (output_p != NULL) {
            break;
        }
    }
    char lrc_filename[128] = { 0 };
    strcat(lrc_filename, key);
    strcat(lrc_filename, ".lrc");
    /* printf("%s\n", lrc_filename); */
    /* printf("%s\n", t); */
    /* printf("target_file: %s\n", t); */
    FILE* fp;
    if (target_file == NULL) {
        fp = fopen(lrc_filename, "wb");
        /* printf("use lrc_filename\n"); */
    } else {
        fp = fopen(t, "wb");
        free(t);
        t = NULL;
        /* printf("use target_file: %s\n", t); */
    }
    if (fp == NULL) {
        perror("can't open file!!\n");
        return ERROR_CODE_LYRIC_OPENFILE;
    }
    /* printf("open file success!!\n"); */
    fwrite(output_p, sizeof(char), strlen(output_p), fp);
    fclose(fp);
    return 0;
}
